//axios基础封装
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";
import {useRouter} from "vue-router";

const Router = useRouter();


const httpInstance = axios.create({
    baseURL: 'http://localhost:8080/api' // 基地址
})

//拦截器
httpInstance.interceptors.request.use(config => {
    // 2. 按照后端的要求拼接token数据
    const token = localStorage.getItem('Authorization')
    if (token) {
        config.headers.Authorization = `${token}`
    }
    return config
}, e => Promise.reject(e))

//响应拦截器
httpInstance.interceptors.response.use(response => {
    let responseData = response.data
    let responseCode = responseData.code

    //判断用户当前token是否过期，过期则清空localStorage中的token和过期时间
    if (responseCode === 401) {
        // 清空local
        localStorage.removeItem("Authorization")
        localStorage.removeItem("password")
        //弹出提示框
        ElMessage.error("登录状态过期,请重新登录");
    } else if (responseCode !== 200) {
        ElMessage.error(responseData.message)
    }

    return responseData
})


export default httpInstance